package com.yxq.mdt.app.modules.spikedetail.ui;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.blankj.utilcode.util.ToastUtils;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.IntentHelper;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.market.bean.MallGoodsBean;
import com.yxq.mdt.app.modules.market.ui.MainMallGoodsListAdapter;
import com.yxq.mdt.app.modules.picturebrowse.ui.PictureActivity;
import com.yxq.mdt.app.modules.spikedetail.bean.GoodsCommentBean;
import com.yxq.mdt.app.modules.spikedetail.bean.SpikeGoodsDetailBean;
import com.yxq.mdt.app.modules.spikedetail.model.SpikeGoodsModel;
import com.yxq.mdt.app.modules.spikedetail.presenter.ISpikeGoodsContract;
import com.yxq.mdt.app.modules.spikedetail.presenter.SpikeGoodsPresenter;
import com.yxq.mdt.app.utils.DisplayUtil;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.widgets.tagview.TagView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 商品详情-首页
 */
public class SpikeGoodsDetailIndexFragment extends BaseFragment<SpikeGoodsPresenter> implements ISpikeGoodsContract.View {


    @BindView(R.id.goods_img_banner)
    ConvenientBanner goodsImgBanner;
    @BindView(R.id.goods_tv_price)
    TextView goodsTvPrice;
    @BindView(R.id.goods_tv_sale_count)
    TextView goodsTvSaleCount;
    @BindView(R.id.goods_detail_tags)
    TagView goodsDetailTags;
    @BindView(R.id.goods_detail_tv_goods_name)
    TextView goodsDetailTvGoodsName;
    @BindView(R.id.goods_detail_tv_goods_label)
    TextView goodsDetailTvGoodsLabel;
    SpikeGoodsDetailBean mGoodsDetailBean;
    @BindView(R.id.goods_detail_tv_service)
    TextView goodsDetailTvService;
    @BindView(R.id.goods_detail_tv_recommend_count)
    TextView goodsDetailTvRecommendCount;
    @BindView(R.id.goods_detail_tv_recommend_more)
    TextView goodsDetailTvRecommendMore;
    @BindView(R.id.goods_detail_recycler_view_commend)
    RecyclerView goodsDetailRecyclerViewCommend;
    @BindView(R.id.goods_detail_tv_recommend)
    TextView goodsDetailTvRecommend;
    @BindView(R.id.goods_detail_recycler_view_recommend)
    RecyclerView goodsDetailRecyclerViewRecommend;
    SpikeGoodsCommentListAdapter goodsCommentListAdapter;
    List<GoodsCommentBean.ListBean> listBeanList;

    @Override
    protected int attachLayoutId() {
        return R.layout.fragment_spike_goods_detail_index;
    }

    @Override
    protected SpikeGoodsPresenter getPresenter() {
        return new SpikeGoodsPresenter(this, new SpikeGoodsModel());
    }

    @Override
    public void initView(View view) {
        int screenWidth = DisplayUtil.getScreenRelatedInformation(getContext());
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) goodsImgBanner.getLayoutParams();
        layoutParams.height = screenWidth;
        goodsImgBanner.setLayoutParams(layoutParams);
        goodsImgBanner.setPageIndicator(new int[]{R.drawable.shape_banner_selector_unchecked, R.drawable.shape_banner_selector_checked});

        goodsCommentListAdapter = new SpikeGoodsCommentListAdapter(R.layout.layout_goods_detail_comment_item_layout, listBeanList);
        goodsDetailRecyclerViewCommend.setLayoutManager(new LinearLayoutManager(mContext));
        goodsDetailRecyclerViewCommend.setAdapter(goodsCommentListAdapter);
    }

    @Override
    public void initData() {
        mPresenter.getGoods(getArguments().getString("id"));
//        mPresenter.getGoodsRecommend(getArguments().getString("id"));
        mPresenter.getCommentList(getArguments().getString("id"), 1);
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void onLoadSuccess(SpikeGoodsDetailBean goodsDetailBean) {
        if (goodsDetailBean == null) {
            return;
        }
        mGoodsDetailBean = goodsDetailBean;
        initGoodsImages(goodsDetailBean);
        initGoodsInfo(goodsDetailBean);
    }

    /**
     * 初始化商品文字介绍信息
     *
     * @param goodsDetailBean
     */
    private void initGoodsInfo(SpikeGoodsDetailBean goodsDetailBean) {
        goodsDetailTvGoodsName.setText(goodsDetailBean.getName());
        goodsTvPrice.setText(String.format("￥%.2f", goodsDetailBean.getMiaosha().getMiaosha_price()));
        goodsTvSaleCount.setText(String.format("销量:%s", goodsDetailBean.getSales_volume()));
        if (goodsDetailBean.getService_list() != null) {
            goodsDetailTvGoodsLabel.setText(goodsDetailBean.getService_list().size() > 0 ? goodsDetailBean.getService_list().toString() : "");
        }
    }

    /**
     * 初始化商品滚动图片
     *
     * @param goodsDetailBean
     */
    private void initGoodsImages(SpikeGoodsDetailBean goodsDetailBean) {
        if (goodsDetailBean == null) {
            return;
        }
        if (goodsDetailBean.getPic_list() == null) {
            return;
        }
        goodsImgBanner.setPages(new CBViewHolderCreator() {
            @Override
            public Holder createHolder(View itemView) {

                return new ImageHolderView(itemView);
            }

            @Override
            public int getLayoutId() {
                return R.layout.layout_banner_item;
            }
        }, goodsDetailBean.getPic_list());
        goodsImgBanner.startTurning();
        goodsImgBanner.setOnItemClickListener(position -> {
            //预览
            Intent intent = new Intent(getContext(), PictureActivity.class);
            intent.putExtra("position", position);
            ArrayList<String> images = new ArrayList<>();
            for (SpikeGoodsDetailBean.PicListBean photoImgFile : goodsDetailBean.getPic_list()) {
                images.add(photoImgFile.getPic_url());
            }
            intent.putExtra("images", images);
            startActivity(intent);
        });
    }

    @Override
    public void onLoadFailed(String err) {
        ToastUtils.showShort(err);
    }

    @Override
    public void onLoadRecommendSuccess(MallGoodsBean mallGoodsBean) {
        //推荐商品
        MainMallGoodsListAdapter mainMallGoodsListAdapter = new MainMallGoodsListAdapter(R.layout.layout_item_goods_list_ver_layout, mallGoodsBean.getList());
        mainMallGoodsListAdapter.setRow(3);
        goodsDetailRecyclerViewRecommend.setLayoutManager(new GridLayoutManager(mContext, 3));
        goodsDetailRecyclerViewRecommend.setAdapter(mainMallGoodsListAdapter);
        mainMallGoodsListAdapter.setOnItemClickListener((adapter, view, position) -> {
            //跳转商品详情
            Bundle bundle = new Bundle();
            bundle.putString("id", mainMallGoodsListAdapter.getData().get(position).getId() + "");
            IntentHelper.arouter(RouteTable.ROUTER_ACTIVITY_GOODS_DETAIL, bundle);
        });
        if (goodsDetailRecyclerViewRecommend.getItemDecorationCount() == 0) {
            goodsDetailRecyclerViewRecommend.addItemDecoration(new GridSpacingItemDecoration(3, 8, false));
        }
    }

    @Override
    public void onLoadRecommendFailed(String err) {

    }

    @Override
    public void onAddSuccess(String err) {
        ToastUtils.showShort(err);
        if (getGoodsDetailBean() != null) {
            getGoodsDetailBean().setIs_favorite(1);
            collectStatus.setImageResource(R.mipmap.ic_collect);
        }
    }

    @Override
    public void onAddFailed(String err) {
        ToastUtils.showShort(err);
    }

    @Override
    public void onRemoveSuccess(String err) {
        ToastUtils.showShort(err);
        if (getGoodsDetailBean() != null) {
            getGoodsDetailBean().setIs_favorite(0);
            collectStatus.setImageResource(R.mipmap.ic_collect);
        }
    }

    @Override
    public void onRemoveFailed(String err) {
        ToastUtils.showShort(err);
    }

    @Override
    public void onLoadCommentSuccess(GoodsCommentBean goodsCommentBean) {
        if (goodsCommentBean == null) {
            return;
        }
        if (goodsCommentBean.getList() == null) {
            return;
        }
        bindUI(goodsCommentBean);
        List<GoodsCommentBean.ListBean> commentBeanList = new ArrayList<>();

        for (int i = 0; i < goodsCommentBean.getList().size(); i++) {
            commentBeanList.add(goodsCommentBean.getList().get(i));
            if (i == 1) {
                break;
            }
        }
        goodsCommentListAdapter.setNewData(commentBeanList);

    }

    private void bindUI(GoodsCommentBean goodsCommentBean) {
        goodsDetailTvRecommendCount.setText(String.format("商品评价(%d)", (goodsCommentBean.getPage_count() * goodsCommentBean.getRow_count())));
    }

    @Override
    public void onLoadCommentFailed(String err) {

    }

    @Override
    public void onAddCartSuccess(String result) {

    }

    @Override
    public void onAddCartFailed(String err) {

    }

    ImageView collectStatus;

    public void add(ImageView collectStatus) {
        this.collectStatus = collectStatus;
        if (getGoodsDetailBean() != null) {
            if (getGoodsDetailBean().getIs_favorite() == 1) {
                mPresenter.favoriteRemove(getArguments().getString("id"));
            } else {
                mPresenter.favoriteAdd(getArguments().getString("id"));
            }
        }

    }

    /**
     * 返回商品详情
     *
     * @return
     */
    public SpikeGoodsDetailBean getGoodsDetailBean() {
        return mGoodsDetailBean;
    }

    @OnClick(R.id.goods_detail_tv_recommend_more)
    public void onViewClicked() {
        SpikeGoodsDetailTabActivity goodsDetailTabActivity = (SpikeGoodsDetailTabActivity) getActivity();
        goodsDetailTabActivity.setCurrentTab(2);
    }

    /**
     * 图片轮转实现
     */
    class ImageHolderView extends Holder<SpikeGoodsDetailBean.PicListBean> {
        private ImageView imageView;

        public ImageHolderView(View itemView) {
            super(itemView);
        }

        @Override
        protected void initView(View itemView) {
            imageView = itemView.findViewById(R.id.banner_image);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        }

        @Override
        public void updateUI(SpikeGoodsDetailBean.PicListBean bean) {
            GlideHelper.setLoadImage(mContext, bean.getPic_url(), R.color.gray, imageView);
        }
    }
}